﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using Application.Repositories;

namespace Application
{
    public class MainWindowViewModel
    {
        private readonly IRepository<Product> _productRepository;
        private readonly IWindow _window;
        private readonly ObservableCollection<Product> _products;
        private readonly RelayCommand _refreshCommand;
        private readonly RelayCommand _newCommand;

        public MainWindowViewModel(IRepository<Product> productRepository, IWindow window)
        {
            if (productRepository == null) throw new ArgumentNullException("productRepository");
            if (window == null) throw new ArgumentNullException("window");

            _productRepository = productRepository;
            _window = window;
            _products = new ObservableCollection<Product>();
            _refreshCommand = new RelayCommand(RefreshProducts);
            _newCommand = new RelayCommand(New);

            RefreshProducts(new object());
        }

        public ICommand NewCommand
        {
            get { return _newCommand; }
        }

        public ICommand RefreshCommand
        {
            get { return _refreshCommand; }
        }

        private void New(object parameter)
        {
            var editor = new ProductEditorViewModel(0);
            editor.Name = Environment.UserName;

            if(_window.CreateChild(editor).ShowDialog() ?? false)
            {
                _productRepository.Add(editor);
                RefreshProducts(new object());
            }
        }

        public ObservableCollection<Product> Products { get { return _products; } }

        private void RefreshProducts(object parameter)
        {
            _products.Clear();
            
            foreach(var product in _productRepository.FindAll())
            {
                _products.Add(product);
            }
        }
    }
}